package com.xz;

/**
 * @author XZ
 * @create 2021-04-20 09:56
 * https://leetcode-cn.com/problems/remove-linked-list-elements/
 */
public class _203_移除链表元素 {
    /**
     * 自己写的，有错误
     *
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements1(ListNode head, int val) {
        if (head == null) return head;
        if (head.val == val) {
            head = head.next;
        }
        ListNode prev = head;
        while (prev.next != null) {
            if (prev.next.val == val) {
                ListNode tmp = prev.next.next;
                prev.next = tmp;
            }
            prev = prev.next;
        }
        return head;
    }

    public ListNode removeElements3(ListNode head, int val) {
        while (head != null && head.val == val) {
            head = head.next;
        }
        ListNode prev = head;
        if (prev != null) {
            while (prev.next != null) {
                if (prev.next.val == val)
                    prev.next = prev.next.next;
                else
                    prev = prev.next;
            }
        }
        return head;
    }


    public ListNode removeElements2(ListNode head, int val) {
        ListNode header = new ListNode(-1);
        header.next = head;
        ListNode cur = header;
        while (cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return header.next;
    }
}
